552. Student Attendance Record II
1. Questions
An attendance record for a student can be represented as a string where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:
'A'
: Absent.'L'
: Late.'P'
: Present.
Any student is eligible for an attendance award if they meet both of the following criteria:
- The student was absent (
'A'
) for strictly fewer than 2 days total. - The student was never late (
'L'
) for 3 or more consecutive days.
Given an integer n
, return the number of possible attendance records of length n
that make a student eligible for an attendance award. The answer may be very large, so return it modulo 109 + 7.
2. Examples
Example 1:
Input: n = 2
Output: 8
Explanation: There are 8 records with length 2 that are eligible for an award:
"PP", "AP", "PA", "LP", "PL", "AL", "LA", "LL"
Only "AA" is not eligible because there are 2 absences (there need to be fewer than 2).
Example 2:
Input: n = 1
Output: 3
Example 3:
Input: n = 10101
Output: 183236316
3. Constraints
- 1 <= n <= 105
4. References
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/student-attendance-record-ii 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
5. Solutions
官方的dp
class Solution {
public int checkRecord(int n) {
final int MOD = 1000000007;
int[][][] dp = new int[n + 1][2][3]; // 长度,A 的数量,结尾连续 L 的数量
dp[0][0][0] = 1;
for (int i = 1; i <= n; i++) {
// 以 P 结尾的数量
for (int j = 0; j <= 1; j++) {
for (int k = 0; k <= 2; k++) {
dp[i][j][0] = (dp[i][j][0] + dp[i - 1][j][k]) % MOD;
}
}
// 以 A 结尾的数量
for (int k = 0; k <= 2; k++) {
dp[i][1][0] = (dp[i][1][0] + dp[i - 1][0][k]) % MOD;
}
// 以 L 结尾的数量
for (int j = 0; j <= 1; j++) {
for (int k = 1; k <= 2; k++) {
dp[i][j][k] = (dp[i][j][k] + dp[i - 1][j][k - 1]) % MOD;
}
}
}
int sum = 0;
for (int j = 0; j <= 1; j++) {
for (int k = 0; k <= 2; k++) {
sum = (sum + dp[n][j][k]) % MOD;
}
}
return sum;
}
}